package controllers

import (
	"encoding/json"
	"fmt"
	"log"
	"strconv"
	"strings"

	"github.com/gocolly/colly"
)

type SzCity struct {
	link  string
	metro Metro
}

func SzDeal() {
	// NewSzCity("http://www.szmc.net/ver2/").home("operating")
	city := NewSzCity("http://www.szmc.net/ver2/")
	city.loop()
	city.metro.CityKey = "SZ"
	obj, _ := json.Marshal(city.metro)
	CreateFile("./data/shenzhen1.json", obj)
}
func NewSzCity(link string) *SzCity {
	var metro Metro
	ReadJsonFileToStruct("./data/shenzhen.json", &metro)
	return &SzCity{link, metro}
}

func (city *SzCity) home(link string) {
	c := colly.NewCollector()
	c.OnHTML("#query ol", func(e *colly.HTMLElement) {
		// log.Printf("Contains %s", e.Text)
		e.ForEach("a", func(_ int, el *colly.HTMLElement) {
			// log.Printf("ForEach %s", el.Text)
			// log.Printf("Contains %s", el.Text)
			// log.Println("ForEach:", el.Text, el.Attr("href"))
			// city.bus(el.Attr("href"))
			// start := el.Attr("href")
			// strings.Split(start, "?")

			// city.bus(el.Attr("href"))
		})

	})
	log.Printf("Home %s", city.link+link)
	c.Visit(city.link + link)

}

func (city *SzCity) line(link string) {
	c := colly.NewCollector()
	c.OnHTML("#siteList", func(e *colly.HTMLElement) {
		// log.Println("zhandian_ju:", e.Text)
		e.ForEach("a", func(_ int, el *colly.HTMLElement) {
			log.Println("chuk:", el.Text)
		})
		e.ForEach("div", func(_ int, el *colly.HTMLElement) {
			log.Println("chuk1:", el.Text)
		})
	})

	log.Printf("Line %s", city.link+link)
	c.Visit(city.link + link)
}

func (city *SzCity) loop() {
	for lineKey, line := range city.metro.LineData {
		// fmt(operating/search?searchkey=&scode=0801&xl=8)
		log.Println("line", line.LineId, line.LineName)
		linecode := "0"
		if len(line.LineId) == 1 {
			linecode = linecode + line.LineId
		} else {
			linecode = line.LineId
		}
		for stageKey, stage := range line.Stages {
			stagecode := "0"
			indexstr := strconv.Itoa(stage.Index)
			if len(indexstr) == 1 {
				stagecode = stagecode + indexstr
			} else {
				stagecode = indexstr
			}
			link := fmt.Sprintf("operating/search?searchkey=&scode=%s%s&xl=%s", linecode, stagecode, line.LineId)
			index := make(map[string]EntrysRes)
			if err := city.bus(link, index); err != nil {
				log.Println("bus", err, stage)
			}
			for doorKey, door := range stage.EntrysRes {
				if v, ok := index[door.EntryName]; ok {
					city.metro.LineData[lineKey].Stages[stageKey].EntrysRes[doorKey].BusStages = v.BusStages
				}
			}
			// obj, _ := json.Marshal(city.metro)
			// CreateFile("./data/shenzhen1.json", obj)
			// os.Exit(0)

			// log.Println("index", index)
		}
	}
}
func (city *SzCity) bus(link string, index map[string]EntrysRes) error {
	c := colly.NewCollector()
	c.OnHTML(".t_table_bus tbody tr", func(e *colly.HTMLElement) {
		var bus BusStages
		var entrysRes EntrysRes
		e.ForEach("th", func(_ int, el *colly.HTMLElement) {
			data := strings.TrimSpace(el.Text)
			// log.Println("table tbody tr th:", data)
			infos := strings.Split(data, "\n")
			doorName := strings.TrimSpace(strings.Trim(infos[0], "地铁出口："))
			busName := ""
			if len(infos) > 1 {
				busName = strings.TrimSpace(strings.Replace(infos[1], "公交站名：", "", -1))
			}
			entrysRes.EntryName = doorName
			bus.Name = busName
			// log.Println("doorName:", doorName)
			// log.Println("busName:", busName)
		})

		e.ForEach("td", func(_ int, el *colly.HTMLElement) {
			data := strings.TrimSpace(el.Text)
			// log.Println("td:", strings.Split(data, ","))
			if strings.Contains(data, ",") {
				bus.Bus = strings.Split(data, ",")
			} else {
				bus.Bus = strings.Split(data, "/")
			}
		})
		entrysRes.BusStages = append(entrysRes.BusStages, bus)
		index[entrysRes.EntryName] = entrysRes

	})
	req := city.link + link
	err := c.Visit(req)
	return err
}
